package com.xuecheng.content.service.impl;


import com.xuecheng.content.config.MinioProperties;
import freemarker.template.Configuration;
import freemarker.template.Template;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.ByteArrayInputStream;
import java.util.Map;

@Service
public class PublishHtmlService {

    @Autowired
    Configuration configuration;

    @Autowired
    MinioClient minioClient;

    @Autowired
    MinioProperties minioProperties;

    @Async
    public void publish (Map preview,Long coursePubId) throws Exception {
        //第二步：生成HTML页面，存入到minio中
        //1.获取模板
        Template template = configuration.getTemplate("learing_article.ftl");
        //2.调用工具类，将模板和数据静态化处理，获取字符串
        String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, preview);
        //3.数据流处理--和minio绑定
        ByteArrayInputStream is = new ByteArrayInputStream(content.getBytes());
        //4.上传到minio
        //4.1 指定上传文件位置
        String filePath = "/pages/" + coursePubId + ".html";
        //4.2 创建上传参数
        PutObjectArgs objectArgs = PutObjectArgs.builder()
                .contentType("text/html") //文件类型
                .stream(is,is.available(),-1)  //文件流
                .bucket(minioProperties.getBucket())   //存储空间
                .object(filePath)  //文件
                .build();
        //4.3 调用方法上传对应的文件
        minioClient.putObject(objectArgs);
    }
}
